from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.manage_notice.models.manage_notice_team import ManageNoticeTeam
from app.manage_notice.models.manage_notice_user import ManageNoticeUser
from app.manage_notice.models.manage_notice_department import ManageNoticeDepartment

class ManageNoticeTeamHandler():
    """  notice team Handler
    """
    def __init__(self):
        pass


    def get_notice_team_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取通知组信息
        """
        try:
            field_info = {field: value}
            order_info = {"name": "asc"}
            result = ManageNoticeTeam.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.error(f"get notice team search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get notice team search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result


    def get_notice_team_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取通知组信息
        """
        try:
            result = ManageNoticeTeam.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.error(f"get notice team match, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get notice team match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def add_notice_team(self, db: Session, data: dict):
        """
        创建通知组
        """
        try:
            notice_team_object = ManageNoticeTeam.get_object_by_name(db, data["name"])
            if notice_team_object:
                # 如果存在， 则异常返回
                logger.error(f"add notice team failed,name:{data['name']} was exist")
                return False

            users = []
            for user_uuid in data.pop("users_uuid"):
                notice_user_object = ManageNoticeUser.get_object_by_uuid(db, user_uuid)
                if not notice_user_object:
                    logger.error(f"add notice team failed, user_uuid:{user_uuid} not exist")
                    return False
                users.append(notice_user_object)
            data["users"] = users

            result = ManageNoticeTeam.add(db, data)
            if not result:
                logger.error(f"add notice team to database failed")
                return False
        except Exception as e:
            message = f"add notice team error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def update_notice_team(self, db: Session, data: dict):
        """
        修改通知组信息
        """
        try:
            notice_team_object = ManageNoticeTeam.get_object_by_uuid(db, data["uuid"])
            if not notice_team_object:
                # 如果不存在， 则异常返回
                logger.error(f"update notice team failed, name:{data['name']} not exist")
                return False

            # 更新通知组内的通知人
            users = []
            for user_uuid in data.pop("users_uuid"):
                notice_user_object = ManageNoticeUser.get_object_by_uuid(db, user_uuid)
                if not notice_user_object:
                    logger.error(f"update notice team failed, user_uuid:{user_uuid} not exist")
                    return False
                users.append(notice_user_object)
            notice_team_object.users = users
            db.add(notice_team_object)
            db.commit()
            db.refresh(notice_team_object)

            # 更新通知组本身的信息
            result = ManageNoticeTeam.update(db, data)
            if not result:
                logger.error(f"update notice team to database failed")
                return False
        except Exception as e:
            message = f"update notice team error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def delete_notice_team(self, db: Session, data: dict):
        """
        删除通知组信息
        """
        try:
            notice_team_object = ManageNoticeTeam.get_object_by_uuid(db, data['uuid'])
            if not notice_team_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete notice team failed,uuid:{data['uuid']} not exist")
                return False

            # 通知组内有用户不能删除
            if len(notice_team_object.users) != 0:
                # 如果不存在， 则异常返回
                logger.error(f"delete notice team failed, uuid:{data['uuid']} is not empty")
                return False

            # 有部门负责人引用不能删除
            departments_info = ManageNoticeDepartment.get_object_info_by_notice_team(db, data['uuid'])
            if len(departments_info) != 0:
                # 如果不存在， 则异常返回
                logger.error(f"delete notice team failed, uuid:{data['uuid']} used by the departments")
                return False

            # 删除通知用户组
            ManageNoticeTeam.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete notice team error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True




